import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ResultUtils } from 'src/common/utils/result.utils';
import { Repository } from 'typeorm';
import { Classify } from './classify.entity';
import { CreateClassifyDto } from './dto/create-classify.dto';
import { UpdateClassifyDto } from './dto/update-classify.dto';

@Injectable()
export class ClassifyService {
  constructor(@InjectRepository(Classify) private classifyRepository:Repository<Classify>){}
  async create(createClassifyDto: CreateClassifyDto) {
    const classify = await this.classifyRepository.create(createClassifyDto);
    const result = await this.classifyRepository.save(classify);
    return ResultUtils.success(result.id);
  }

  async findAll(isAdmin:boolean) {
    const queryBuilder = this.classifyRepository.createQueryBuilder('classify');
    if(!isAdmin){
      queryBuilder.andWhere('status=:status',{status:1});
    }
    queryBuilder.orderBy('sort','DESC').addOrderBy('update_time','DESC');
    return ResultUtils.success(await queryBuilder.getMany());
  }

  async findOne(id: number,isAdmin:boolean) {
    const queryBuilder = this.classifyRepository.createQueryBuilder('classify').andWhere('id=:id',{id});
    if(!isAdmin) {
      queryBuilder.andWhere('status=:status',{status:1});
    }
    return ResultUtils.success(await queryBuilder.getOne());
  }

  async update(id: number, updateClassifyDto: UpdateClassifyDto) {
    const classify = await this.classifyRepository.findOne({ where: {id} });
    const newClassify = this.classifyRepository.merge(classify,updateClassifyDto);
    return ResultUtils.success(await this.classifyRepository.save(newClassify));
  }

  async getRemoveIds(ids:Array<number>,pid:number) {
    const childrens = await this.classifyRepository.createQueryBuilder('classify').andWhere('pid=:pid',{pid}).getMany();
    for(const i of childrens) {
      ids.push(i.id);
      await this.getRemoveIds(ids,i.id);
    }
  }

  async remove(id: number) {
    const ids:Array<number> = [id];
    await this.getRemoveIds(ids,id);
    await this.classifyRepository.delete(ids);
    return ResultUtils.success();
  }
}
